package com.module.home.ui.home.provider

import android.util.Base64
import android.util.Log
import android.view.View
import android.view.View.OnClickListener
import android.widget.TextView
import com.chad.library.adapter.base.provider.BaseItemProvider
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.common.app.data.bean.CommonMessageRelayModel
import com.common.app.data.bean.KeyEvents
import com.common.app.data.bean.home.HomeMainCardModel
import com.common.app.utls.BrotliCompressionEx
import com.common.app.utls.TimeUtils
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.isEmpty
import com.common.base.app.extras.no
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.yes
import com.common.base.utils.JsonUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.ble.data.bean.CusChartData
import com.module.ble.db.table.UserSleepInfo
import com.module.ble.db.table.UserStepsRelatedRecord
import com.module.ble.repo.UserStepsRelatedRecordRepo
import com.module.ble.utils.ServerHealthDataModelType
import com.module.ble.widget.CandlestickChart
import com.module.ble.widget.SleepStageChart
import com.module.home.R
import java.util.Calendar


/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/07/31
 *
 * 描述：活动AI信息卡片
 *
 * 修订历史：
 *
 */
class CloudReminderActivityProvider(override val itemViewType: Int = 2,
                                    override val layoutId: Int = R.layout.home_provider_cloud_reminder_activity_item,
) : BaseItemProvider<HomeMainCardModel>(),OnClickListener {

    // 初始化一天每30分钟的数据（48个30分钟间隔的数据）
    private val stressData = mutableListOf<CusChartData>()

    var commonMessageRelayModel: CommonMessageRelayModel? = null

    init {
        initEmptyShellData()
    }

    override fun convert(helper: BaseViewHolder, item: HomeMainCardModel) {

        val candlestickChart = helper.getView<CandlestickChart>(R.id.candlestickChart)
        candlestickChart.setTouchEnabled(false)
        candlestickChart.setBarRounding(enableTop = true, enableBottom = false)
        // 设置Y轴阶段
        candlestickChart.setYAxisStages(
            floatArrayOf(0f, 1000f), // 阶段分界点
        )

//        candlestickChart?.setXAxisSolidLineEnabled(true)

        // 在代码中设置数据
        candlestickChart.setData(stressData)


        // 设置触摸监听
        candlestickChart.setOnBarTouchListener(object : CandlestickChart.OnBarTouchListener {

            override fun onBarTouched(
                index: Int,
                minValue: Float,
                maxValue: Float,
                timeLabel: String,
                extStr: String
            ) {
                // 处理触摸事件
                Log.d("CandlestickChart", "触摸到柱子: 索引=$index,触摸到: $timeLabel, 值: $maxValue")
            }

            override fun onAverageLineTouched(
                index: Int,
                minValue: Float,
                maxValue: Float,
                timeLabel: String,
                extStr: String
            ) {
                TODO("Not yet implemented")
            }

            override fun onTouchReleased() {
                // 处理触摸释放事件
            }
        })

        helper.setText(R.id.tvTopTitle,item.title)
        helper.setText(R.id.tvTopSummary,item.summary)

        helper.setGone(R.id.totalImprovement,(item.ai_analyze_result==null))

        item.ai_analyze_result?.let { resultIt->
            helper.setGone(R.id.tvImprovementHint, resultIt.improvement.isNullOrEmpty())
            helper.setGone(R.id.tvInfluenceHint, resultIt.impact.isNullOrEmpty())
            helper.setGone(R.id.tvReasonHint, resultIt.reason.isNullOrEmpty())
            helper.setGone(R.id.tvSuggestionHint, resultIt.suggestion.isNullOrEmpty())

            helper.setGone(R.id.tvImprovement, resultIt.improvement.isNullOrEmpty())
            helper.setGone(R.id.tvInfluence, resultIt.impact.isNullOrEmpty())
            helper.setGone(R.id.tvReason, resultIt.reason.isNullOrEmpty())
            helper.setGone(R.id.tvSuggestion, resultIt.suggestion.isNullOrEmpty())

            helper.setText(R.id.tvImprovement,resultIt.improvement)
            helper.setText(R.id.tvInfluence,resultIt.impact)
            helper.setText(R.id.tvReason,resultIt.reason)
            helper.setText(R.id.tvSuggestion,resultIt.suggestion)

            commonMessageRelayModel = CommonMessageRelayModel(webType = item.id, skipPath = item.possible_questions)
            helper.setGone(R.id.tvAiSuggestion, item.possible_questions.isNullOrEmpty())
            helper.setText(R.id.tvAiSuggestion,item.possible_questions)
        }

        item.chart_data.isEmpty().no {
            // 先将Base64字符串解码回字节数组
            val decodedBytes = Base64.decode(item.chart_data, Base64.DEFAULT)
            // 然后解压缩
            BrotliCompressionEx.decompressToString(decodedBytes).let { dataStrIt ->
                doOnIOThread {
                    val tempData: List<UserStepsRelatedRecord> = JsonUtils.fromJsonList(dataStrIt)
                    Log.e("CloudReminderActivityProvider", "dataList----decompressedJson: $dataStrIt")

                    val temporaryData = mutableListOf<CusChartData>()
                    // 遍历到倒数第二条数据（最后一条数据只作为结束时间标识）
                    for ((index, mData) in tempData.withIndex()) {
                        (index > 0).yes {
                            temporaryData.add(CusChartData(
                                createdTime = mData.createdTime,
//                                minValue = (mData.calorie-tempData[index -1].calorie).toFloat(),
                                mValue = mData.step.toFloat(),
                                dayNum = 0
                            ))
                        }
                    }

                    Log.e("CloudReminderActivityProvider", "dataList----decompressedJson2: ${JsonUtils.toJson(temporaryData)}")
                    // 将temporaryData的数据累加到stressData对应的时间范围
                    temporaryData.isNullOrEmpty().no {//将temporaryData的数据根据时间映射到stressData对应的30分钟时间段

                        initEmptyShellData()

                        // 使用temporaryData中第一条数据的日期作为基准日期
                        val firstDataTime = temporaryData.first().createdTime
                        val calendar = Calendar.getInstance()
                        calendar.timeInMillis = firstDataTime
                        calendar.set(Calendar.HOUR_OF_DAY, 0)
                        calendar.set(Calendar.MINUTE, 0)
                        calendar.set(Calendar.SECOND, 0)
                        calendar.set(Calendar.MILLISECOND, 0)
                        val startOfDay = calendar.timeInMillis // 数据当天的0点时间戳

                        Log.d("CloudReminderActivityProvider", "数据基准日期: ${TimeUtils.getYearMonthDayHourMin(startOfDay)}")

                        temporaryData.forEach { tempData ->
                            // 计算该数据属于哪个30分钟时间段
                            val timeFromStartOfDay = tempData.createdTime - startOfDay

                            // 确保时间在当天范围内
                            if (timeFromStartOfDay >= 0 && timeFromStartOfDay < 24 * 60 * 60 * 1000) {
                                // 计算属于第几个30分钟时间段（0-47）
                                val timeSlotIndex = (timeFromStartOfDay / (30 * 60 * 1000)).toInt()

                                // 确保索引在有效范围内
                                if (timeSlotIndex >= 0 && timeSlotIndex < stressData.size) {
                                    // 将temporaryData的mValue累加到对应时间段的stressData中
                                    val currentStressData = stressData[timeSlotIndex]
                                    stressData[timeSlotIndex] = currentStressData.copy(
                                        mValue = currentStressData.mValue + tempData.mValue
                                    )

                                    val timeSlotStart = startOfDay + timeSlotIndex * 30 * 60 * 1000
                                    val timeSlotEnd = timeSlotStart + 30 * 60 * 1000 - 1

                                    Log.d("CloudReminderActivityProvider",
                                        "映射数据: 原始时间=${TimeUtils.getYearMonthDayHourMin(tempData.createdTime)}, " +
                                                "时间段=${TimeUtils.getYearMonthDayHourMin(timeSlotStart)}-${TimeUtils.getYearMonthDayHourMin(timeSlotEnd)}, " +
                                                "索引=$timeSlotIndex, 步数=${tempData.mValue}, " +
                                                "累加后总值=${stressData[timeSlotIndex].mValue}")
                                } else {
                                    Log.w("CloudReminderActivityProvider", "时间段索引超出范围: $timeSlotIndex")
                                }
                            } else {
                                Log.w("CloudReminderActivityProvider", "数据时间超出当天范围: ${TimeUtils.getYearMonthDayHourMin(tempData.createdTime)}")
                            }
                        }

                        // 获取mValue最大的数据
                        val maxValueData = stressData.maxByOrNull { it.mValue }

                        // 获取所有mValue的步数总和
                        val totalSteps = temporaryData.sumOf { it.mValue.toInt() }
                        // 获取所有mValue的卡路里总和
                        val totalCalorie = temporaryData.sumOf { it.minValue.toInt() }

                        // 在UI线程更新界面
                        doOnUiThread {

                            // 设置Y轴阶段
                            candlestickChart.setYAxisStages(
                                floatArrayOf(0f, maxValueData?.mValue ?: 2000f), // 阶段分界点
                            )

                            // 这里可以通知图表更新数据
                            candlestickChart.setData(stressData)

                            helper.setText(R.id.tvSteps,totalSteps.toString())
                            helper.setText(R.id.tvCalorie,totalCalorie.toString())
                        }
                    }
                }
            }
        }

        helper.getView<TextView>(R.id.tvAiSuggestion).setOnClickListener(onClick = this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tvAiSuggestion -> LiveEventBus.get(KeyEvents.KEY_HOME_SCENE_MODE_CONFIG).post(commonMessageRelayModel)
            else -> {
            }
        }
    }

    fun initEmptyShellData(){
        stressData.clear()

        val currentTime = System.currentTimeMillis()
        val startOfDay = currentTime - (currentTime % (24 * 60 * 60 * 1000)) // 当天0点时间戳

        for (index in 0 until 48) {
            val timeOffset = index * 30 * 60 * 1000L // 每30分钟的时间偏移
            val timestamp = startOfDay + timeOffset

            stressData.add(
                CusChartData(
                    createdTime = timestamp,
                    minValue = 0f,
                    mValue = 0f,
                    dayNum = 0
                )
            )
        }
    }
}